<?php

namespace App\Http\Controllers\V1;

use App\Events\BindMobile;
use App\Http\Requests\BindPhoneRequest;
use App\Http\Controllers\Controller;
use App\Http\Requests\WechaetDataRequest;
use App\Models\MemberFlow;
use App\Models\MobileCode;
use App\Models\Order;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MemberController extends Controller
{
    /**
     * 绑定手机号
     *
     * @param BindPhoneRequest $request
     * @return mixed
     */
    public function bindMobile(BindPhoneRequest $request)
    {
        DB::beginTransaction();
        $user = $request->user();
        //如果是用户输入的就验证验证码
        $res = MobileCode::verifyCode($request->input('phone'),$request->input('code'));
        if(!$res)
        {
            return $this->failed('验证码过期或错误');
        }

        $user->phone = ltrim(phone($request->input('phone'), 'CN', 'E164'), '+86');

        if($user->save())
        {
            //绑定发送优惠券
            event(new BindMobile($user,$request->input('form_id', null)));
            DB::commit();
            return $this->success(['user' => $user]);
        } else {
            DB::rollBack();
            return $this->failed('绑定失败');
        }
    }

    /**
     * 绑定授权手机号
     *
     * @param WechaetDataRequest $request
     * @return mixed
     */
    public function bindMiniMobile(WechaetDataRequest $request)
    {
        $user = $request->user();

        $miniProgram = \Wechat::miniProgram();

        $iv = $request->input('iv','');

        $encryptData = $request->input('encryptedData','');
        try{
            $res = $miniProgram->encryptor->decryptData($user->session_key, $iv, $encryptData);
            if(isset($res['phoneNumber']))
            {
                if($user->phone == $res['phoneNumber'])
                {
                    return $this->failed('该手机号已经绑定');
                }
                $user->phone = $res['phoneNumber'];

                if($user->save()) {
                    //绑定发送优惠券
                    event(new BindMobile($user,$request->input('form_id', null)));

                    return $this->success(['user' => $user]);
                } else {
                    return $this->failed('绑定失败');
                }
            }
        }catch (\Exception $exception){
            return $this->failed($exception->getMessage());
        }
    }

    // 会员中心
    public function memberIndex()
    {
        $user = request()->user();

        // 获取订单数量
        $orders = $user->orders()->where('closed', false)->get();

        // 待付款
        $waitPayment = $orders->where('ship_status', Order::SHIP_STATUS_AWAITING_PAYMENT)->count();

        // 待发货
        $waitShip = $orders->where('ship_status', Order::SHIP_STATUS_PENDING)->count();

        //待收货
        $waitReceipt = $orders->where('ship_status', Order::SHIP_STATUS_DELIVERED)->count();

        return $this->success([
            'waitPayment' => $waitPayment,
            'waitShip' => $waitShip,
            'waitReceipt' => $waitReceipt,
        ]);
    }

    /**
     * 我的流水
     *
     * @return mixed
     */
    public function water()
    {
        $data = MemberFlow::where('member_id', Auth::id())->where(function ($query) {
            if (request()->type) {

                $query->where('type', request()->type);
            }
        })->orderByDesc('created_at')->paginate(10);
        return $this->success($data);
    }

    // 获取用户信息
    public function userinfo() {
        return $this->success(request()->user());
    }
}
